package com.gitlab.techschool.pcbook.service;


import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class DiskImageStore implements ImageStore {

    private final String imageFolder;
    private ConcurrentHashMap<String, ImageMetadata> data;

    public DiskImageStore(String imageFolder) {
        this.imageFolder = imageFolder;
        this.data = new ConcurrentHashMap<>(0);
    }

    @Override
    public String save(String laptopId, String imageType, ByteArrayOutputStream imageData) throws IOException {
        String imageId = UUID.randomUUID().toString();
        String imagePath = String.format("%s/%s.%s", imageFolder, imageId, imageType);

        // 保存到磁盘
        FileOutputStream fileOutputStream = new FileOutputStream(imagePath);
        imageData.writeTo(fileOutputStream);
        fileOutputStream.close();

        ImageMetadata imageMetadata = new ImageMetadata(laptopId, imageType, imagePath);
        data.put(imageId, imageMetadata);
        return imageId;
    }
}
